package com.ruyiadmin.springboot.common.utils.core;

import lombok.experimental.UtilityClass;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;

/**
 * Aes加解密工具类
 *
 * @author RuYiAdmin
 * @since 2022-07-20
 */
@UtilityClass
public class RuYiAesUtil {

    //region 私有属性

    private static final String CHARSET_NAME = "UTF-8";
    private static final String AES_NAME = "AES";
    // 加密模式
    public static final String ALGORITHM = "AES/CBC/PKCS5Padding";

    //endregion

    //region Aes加密

    /**
     * Aes加密
     *
     * @param content 明文
     * @return 密文
     */
    public String encrypt(String content, String aesKey) {
        byte[] result = null;
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            SecretKeySpec keySpec = new SecretKeySpec(aesKey.getBytes(CHARSET_NAME), AES_NAME);
            String iv = StringUtils.reverse(aesKey).toUpperCase().substring(0, 16);
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, paramSpec);
            result = cipher.doFinal(content.getBytes(CHARSET_NAME));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Base64.encodeBase64String(result);
    }

    //endregion

    //region Aes解密

    /**
     * Aes解密
     *
     * @param content 密文
     * @return 明文
     */
    public String decrypt(String content, String aesKey) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            SecretKeySpec keySpec = new SecretKeySpec(aesKey.getBytes(CHARSET_NAME), AES_NAME);
            String iv = StringUtils.reverse(aesKey).toUpperCase().substring(0, 16);
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec);
            return new String(cipher.doFinal(Base64.decodeBase64(content)), CHARSET_NAME);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return StringUtils.EMPTY;
    }

    //endregion

}
